
#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "iconfont.h"

#include <QDateTime>
#include <QGraphicsDropShadowEffect>
#include <QLocale>

#include "tool.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    uiInit();
    dataPanelInit();
    ctlPanelInit();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showEvent(QShowEvent *event)
{
//    QFile qssFile("D:/Desktop/qss/dark.qss"); // 使用资源文件加载QSS文件
//    if (qssFile.open(QFile::ReadOnly | QFile::Text))
//    {
//        QString styleSheet = QLatin1String(qssFile.readAll());
//        qssFile.close();

//        // 设置加载的样式表为全局样式表
//        qApp->setStyleSheet(styleSheet);
//    }

}


void MainWindow::timeShow()
{
    QLocale locale = QLocale::Chinese;
    QDateTime dateTime= QDateTime::currentDateTime();//获取系统当前的时间
    // 获取日期
    QString date = dateTime.toString("yyyy-MM-dd");//格式化时间
    // 获取时间
    QString time = dateTime.toString("hh:mm:ss");//格式化时间
    // 获取周
    QString week =locale.toString(dateTime,QString("ddd"));//格式化时间
    ui->lbl_dateShow->setText(date);
    ui->lbl_timeShow->setText(time);
    ui->lbl_weekShow->setText(week);
}

void MainWindow::uiInit()
{
    this->setWindowIcon(QIcon(":/images/ico.ico"));
    setShadow("#ffffff","#c0c0c0",ui->lbl_titelBac,true);
    tiemPlugsInit();
    linePanelInit();
    ui->btn_set->setFont(IconFont::IconFontInstance()->iconFont);
    ui->btn_set->setText(QChar(0xe600));
    ui->btn_set->setStyleSheet("color:black;font-size:26px;");
}

void MainWindow::dataPanelInit()
{
    temp = new DataPanel(ui->frame_temp);
    temp->setBasicTemplate("#ffffff","#c0c0c0","温度",QChar(0xe88c),"℃");
    humi = new DataPanel(ui->frame_humi);
    humi->setBasicTemplate("#ffffff","#c0c0c0","湿度",QChar(0xe834),"%Rh");
    light = new DataPanel(ui->frame_light);
    light->setBasicTemplate("#ffffff","#c0c0c0","光强",QChar(0xea32),"Lux");
    soil = new DataPanel(ui->frame_soil);
    soil->setBasicTemplate("#ffffff","#c0c0c0","地面潮湿度",QChar(0xea30),"%Rh");
    cfgCom = new CfgCom(this);
    connect(cfgCom,&CfgCom::sendData,this,&MainWindow::receiveData);
}

void MainWindow::ctlPanelInit()
{
    temp_ctl = new ControlPanel(ui->frame_temp_ctl);
    temp_ctl->setBasicTemplate("#ffffff","#c0c0c0","降温","待机中",":/gif/fan.gif");
    connect(temp_ctl,&ControlPanel::sendData,cfgCom,&CfgCom::writeData);
    humi_ctl = new ControlPanel(ui->frame_humi_ctl);
    humi_ctl->setBasicTemplate("#ffffff","#c0c0c0","加湿","待机中",":/gif/wet.gif");
    connect(humi_ctl,&ControlPanel::sendData,cfgCom,&CfgCom::writeData);
    light_ctl = new ControlPanel(ui->frame_light_ctl);
    light_ctl->setBasicTemplate("#ffffff","#c0c0c0","光控","待机中",":/gif/light.gif");
    connect(light_ctl,&ControlPanel::sendData,cfgCom,&CfgCom::writeData);
    soil_ctl = new ControlPanel(ui->frame_soil_ctl);
    soil_ctl->setBasicTemplate("#ffffff","#c0c0c0","水控","待机中",":/gif/water.gif");
    connect(soil_ctl,&ControlPanel::sendData,cfgCom,&CfgCom::writeData);
    ui->comboBox_auto->setCurrentText("自动");

}

void MainWindow::setShadow(QString background_color,QString color,QWidget *widget,bool bac_none,qint64 radius)
{
    //设置具体阴影
    auto shadow_effect = new QGraphicsDropShadowEffect;
    shadow_effect->setOffset(0, 0);
    //阴影颜色
    shadow_effect->setColor(QColor(color));
    //阴影半径
    shadow_effect->setBlurRadius(radius);
    // 控件设置
    widget->setGraphicsEffect(shadow_effect);

    if(bac_none){
        return ;
    }
    QString style = "%1#%2{border:2px solid white;border-radius:%3px;background-color: %4;}";
    widget->setStyleSheet(style.arg(widget->metaObject()->className()).arg(widget->objectName()).arg(radius).arg(background_color));
    qDebug() << style.arg(widget->metaObject()->className()).arg(widget->objectName()).arg(radius).arg(background_color);
}


void MainWindow::dataManageHandle()
{
    // 1. 获取数据控件
//    qDebug() << this->gridLayout_dataManage

}

void MainWindow::tiemPlugsInit()
{
    timer = QSharedPointer<QTimer>(new QTimer(this));
    timer.data()->start(1000);
    connect(timer.data(),&QTimer::timeout,this,&MainWindow::timeShow);
    ui->lbl_timeIcon->setFont(IconFont::IconFontInstance()->iconFont);
    ui->lbl_timeIcon->setText(QChar(0xe648));
    ui->lbl_timeIcon->setStyleSheet("font-size:32px");

    setShadow("#ffffff","#c0c0c0",ui->frame_time);

}

void MainWindow::linePanelInit()
{
    setLine1Panel();
    setLine2Panel();

//    QTimer *timer = new QTimer();
//    connect(timer, &QTimer::timeout,this,[this]{
//        static double constant = 60;
//        int temp = rand() % 5 + 1;
//        int n = rand() % 5;    //产生100以内的随机整数
//        double fn = n / (temp * 1.0);   //产生10以内的随机浮点数，精度为小数点后1位
//        setPanelData(m_line1,constant + fn,constant + fn + 3);
//        setPanelData(m_line2,constant + fn,constant + fn + 3);
//    });
//    timer->start(100);


//    m_line2->xAxis->setTicker(dateTick);
    //    m_line2->plotLayout()->insertRow(0);
}

void MainWindow::addLine(QCustomPlot *costomPlot, QVector<QPair<QString, QColor> > lines)
{
    QSharedPointer<QCPAxisTickerDateTime> dateTick(new QCPAxisTickerDateTime);
    dateTick->setDateTimeFormat("HH:mm:ss");

    costomPlot->xAxis->setTicker(dateTick);
    costomPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes |
                                QCP::iSelectLegend | QCP::iSelectPlottables);//允许鼠标点击拖动
    costomPlot->legend->setVisible(true); // 显示图例
    costomPlot->legend->setBrush(QBrush(Qt::NoBrush));
    for(int index = 0; index < lines.length(); ++index){
        costomPlot->addGraph();
        QPen pen;
        pen.setWidth(2);
        pen.setColor(lines[index].second);
        costomPlot->graph(index)->setName(lines[index].first);
        costomPlot->graph(index)->setPen(pen);
    }
    costomPlot->xAxis->setRange(0,40);
    costomPlot->yAxis->setRange(0,140);
}

void MainWindow::setLine1Panel()
{
    setShadow("#ffffff","#c0c0c0",ui->w1);
    m_line1 = ui->widget_line1;
    QPair<QString, QColor> temp_line;
    temp_line.first = "温度";
    temp_line.second = QColor(255, 59, 50);
    QPair<QString, QColor> humi_line;
    humi_line.first = "湿度";
    humi_line.second = QColor(64, 158, 255);
    QVector<QPair<QString, QColor>> lines;
    lines.append(temp_line);
    lines.append(humi_line);
    addLine(m_line1,lines);
}

void MainWindow::setLine2Panel()
{
    setShadow("#ffffff","#c0c0c0",ui->w2);
    m_line2 = ui->widget_line2;
    QPair<QString, QColor> light_line;
    light_line.first = "光照";
    light_line.second = QColor(251, 197, 49);
    QPair<QString, QColor> soil_line;
    soil_line.first = "地板";
    soil_line.second = QColor(47, 54, 64);
    QVector<QPair<QString, QColor>> lines;
    lines.append(light_line);
    lines.append(soil_line);
    addLine(m_line2,lines);
}

void MainWindow::setPanelData(QCustomPlot *costomPlot, double data_0, double data_1)
{
    //key的单位是秒
    double x_time = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
    costomPlot->xAxis->setRange(x_time+0.25, 8, Qt::AlignRight);//设定x轴的范围
    costomPlot->yAxis->rescale(true);

    costomPlot->graph(0)->addData(x_time, data_0);//添加数据1到曲线1
    costomPlot->graph(1)->addData(x_time, data_1);//添加数据1到曲线1
    costomPlot->graph(0)->rescaleValueAxis(true);//添加数据1到曲线1
    costomPlot->graph(1)->rescaleValueAxis(true);//添加数据1到曲线1
    costomPlot->replot();
}


void MainWindow::on_btn_set_clicked()
{
    cfgCom->show();
}

void MainWindow::receiveData(QByteArray data)
{
    // 获取全部数据
    qDebug() << "获取数据" << data;
    TOOL::JSON * json = new TOOL::JSON(data);
    if(json->IsEmpty()){
        return;
    }
    bool temp_state = static_cast<bool>(json->Get<int>("state","tempState"));
    bool humi_state = static_cast<bool>(json->Get<int>("state","humiState"));
    bool light_state = static_cast<bool>(json->Get<int>("state","lightState"));
    bool soil_state = static_cast<bool>(json->Get<int>("state","soilState"));

    temp->setValue(QString("%1").arg(json->Get<int>("data","temp")),temp_state);
    humi->setValue(QString("%1").arg(json->Get<int>("data","humi")),humi_state);
    setPanelData(m_line1,json->Get<int>("data","temp"),json->Get<int>("data","humi"));
    light->setValue(QString("%1").arg(json->Get<int>("data","light")),light_state) ;
    soil->setValue(QString("%1").arg(json->Get<int>("data","soil")),soil_state);
    setPanelData(m_line2,json->Get<int>("data","light"),json->Get<int>("data","soil"));
    // 默认自动控制
    if(json->Get<int>("state","ctrl_model")){
        ui->comboBox_auto->setCurrentText("自动");
        // 设置控制面板
        temp_ctl->setState(temp_state);
        humi_ctl->setState(humi_state);
        light_ctl->setState(light_state);
        soil_ctl->setState(soil_state);
        return;
    }
    ui->comboBox_auto->setCurrentText("手动");

}

void MainWindow::on_comboBox_auto_currentTextChanged(const QString &arg1)
{
    QString cmd = "{\"%1\":\"%2\"}";
    // 切换模式
    if(arg1 == "自动"){
        cmd.arg("On");
        cfgCom->writeData(cmd.arg("auto","On"));
        temp_ctl->disableCtrl(true);
        humi_ctl->disableCtrl(true);
        light_ctl->disableCtrl(true);
        soil_ctl->disableCtrl(true);
    }
    else{
        cmd.arg("Off");
        cfgCom->writeData(cmd.arg("auto","Off"));
        temp_ctl->disableCtrl(false);
        humi_ctl->disableCtrl(false);
        light_ctl->disableCtrl(false);
        soil_ctl->disableCtrl(false);
    }
}



void MainWindow::on_comboBox_model_currentTextChanged(const QString &arg1)
{
    if(arg1 == "日间模式"){
        QFile qssFile(":/qss/light.qss"); // 使用资源文件加载QSS文件
        if (qssFile.open(QFile::ReadOnly | QFile::Text))
        {
            QString styleSheet = QLatin1String(qssFile.readAll());
            qssFile.close();

            // 设置加载的样式表为全局样式表
            qApp->setStyleSheet(styleSheet);
        }
    }
    else{
        QFile qssFile(":/qss/dark.qss"); // 使用资源文件加载QSS文件
        if (qssFile.open(QFile::ReadOnly | QFile::Text))
        {
            QString styleSheet = QLatin1String(qssFile.readAll());
            qssFile.close();

            // 设置加载的样式表为全局样式表
            qApp->setStyleSheet(styleSheet);
        }
    }
}

